package com.yueshop.ware.listener;

import com.rabbitmq.client.Channel;
import com.yueshop.common.mq.StockLockedTo;
import com.yueshop.common.to.OrderTo;
import com.yueshop.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;


@Slf4j
@Service
@RabbitListener(queues = {"stock.release.stock.queue"})
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    //库存解锁场景1
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        log.info("*********************************收到库存解锁的消息*********************************");
        //调用解锁方法
        try {
            wareSkuService.unlock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
           channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    //库存解锁场景2
    //下单成功,但是没有在指定时间之内完成支付 订单过期自动取消了订单.或者是用户手动取消订单
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        log.info("*********************************收到订单关闭, 准备解锁库存*********************************");
        //调用解锁方法
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
